package com.hk.commons.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.hk.commons.dict.DictService;
import com.hk.commons.jackson.annotations.DictField;
import com.hk.commons.util.SpringContextHolder;

import java.io.IOException;
import java.util.Objects;

/**
 * 数据字典序列化
 *
 * @author Kevin
 * @date 2024-11-21 11:25
 */
public class DictSerializer extends StdSerializer<Number> {

    private final DictField dictField;

    private DictService dictService;

    protected DictSerializer(DictField dictField) {
        super(Number.class);
        this.dictField = dictField;
    }

    public DictService getDictService() {
        if (Objects.isNull(dictService)) {
            dictService = SpringContextHolder.getBean(DictService.class);
        }
        return dictService;
    }

    @Override
    public Class<Number> handledType() {
        return Number.class;
    }

    @Override
    public void serialize(Number value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeNumber(String.valueOf(value));
        try {
            DictService service = getDictService();
            String codeValue = service.getCodeName(dictField.value(), value);
            gen.writeStringField(gen.getOutputContext().getCurrentName().concat("Name"), codeValue);
        } catch (Exception e) {
            // ignore
        }
    }
}
